package com.hh.erp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hh.erp.entity.SysDept;
import com.hh.erp.entity.SysMenu;
import com.hh.erp.entity.vo.SysDeptVo;
import com.hh.erp.entity.vo.TreeSelectVo;
import com.hh.erp.mapper.SysDeptMapper;
import com.hh.erp.service.SysDeptService;
import com.hh.erp.util.JsonUtil;
import com.hh.erp.util.StringUtil;
import com.hh.erp.util.http.AjaxResult;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author zhb
 * @since 2024-03-31
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    @Override
    public List<TreeSelectVo> selectDeptTreeList() {
        // 查出所有数据
        List<SysDept> depts =  this.baseMapper.selectDeptList();
        List<SysDeptVo> voDepts = new ArrayList<>();
        depts.stream().forEach(p->{
            SysDeptVo vo = new SysDeptVo();
            BeanUtils.copyProperties(p,vo);
            voDepts.add(vo);
        });
        List<SysDeptVo> deptTrees = restDeptTree(voDepts,0L);
        List<TreeSelectVo> treeList = deptTrees.stream().map(TreeSelectVo::new).collect(Collectors.toList());
        return treeList;
    }

    public static List<SysDeptVo> restDeptTree(List<SysDeptVo> depts, Long parentId) {
        List<SysDeptVo> list = depts.stream().filter(p-> StringUtil.Equals(p.getParentId(),parentId)).collect(Collectors.toList());
        list.stream().filter(p->StringUtil.Equals(p.getParentId(),parentId)).forEach(p->{
            p.setChildren(restDeptTree(depts,p.getDeptId()));
        });
        return list;
    }
}
